<template>
    <tableLayout :columns="columns" :operationShow="true" :get="getInnerFormPageData" :selectItem="selectItem" :rules="rules"
        ref="layout" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <template #button>
            <a-button type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
            <a-button style="margin-left: 20px" @click="edit" :disabled="selectedRowKeys.length !== 1">修改</a-button>
            <a-button type="primary" style="margin-left: 20px" @click="del" :disabled="selectedRowKeys.length !== 1"
                danger>删除</a-button>
        </template>

        <template #operationMore="item">
            <a @click="edit(null, item.value.record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="del(null, item.value.record.Id)">删除</a>
        </template>

        <template v-slot:custom="data">
            <a-input v-model:value="data.formData[data.key]" />
        </template>
    </tableLayout>

    <a-modal :title="formState.Id ? '编辑表单' : '新增表单'" v-model:visible="modal_visible" :confirm-loading="confirmLoading"
        @ok="modal_handleOk" width="1200px">
        <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"
            layout="inline" class="comform">
            <a-form-item label="表单名称" style="width: calc(50% - 20px);" class="form__item" name="FormName">
                <a-input v-model:value="formState.FormName" placeholder="表单名称" />
            </a-form-item>
            <a-form-item label="表单路径" style="width: calc(50% - 20px);" class="form__item" name="FormPath">
                <a-input v-model:value="formState.FormPath" placeholder="表单路径" />
            </a-form-item>
            <a-form-item label="表单编码" style="width: calc(50% - 20px);" class="form__item" name="FormCode">
                <a-input v-model:value="formState.FormCode" :readonly="true" placeholder="表单编码">
                    <template #suffix>
                        <a-tooltip title="复制表单编码">
                            <CopyTwoTone style="color: rgba(0, 0, 0, 0.45)" @click="onCopyTableCode" />
                        </a-tooltip>
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item label="是否有效" style="width: calc(50% - 20px);" class="form__item" name="IsValid">
                <a-checkbox v-model:checked="formState.IsValid" />
            </a-form-item>

            <a-form-item label="备注" style="width: calc(100% - 20px);" class="form__item" name="Remark"
                :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-textarea v-model:value="formState.Remark" placeholder="备注" :rows="4" />
            </a-form-item>
        </a-form>      
    </a-modal>

</template>

<script lang="ts" setup>
import { ref, UnwrapRef, reactive, nextTick, h } from 'vue';
import { notification, message } from 'ant-design-vue';
import { InnerFormInput } from '@/types/api/workflow/innerform';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { getInnerFormPageData,deleteInnerForm,saveOrUpdateInnerForm } from '@/api/workflow/innerform';
import { CustomIdPrefix } from '@/components/id/idGenerater';
import { CopyTwoTone, PlusOutlined } from '@ant-design/icons-vue';

const layout = ref();
const modal_visible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const formRef = ref()

//表单对象
const formState: UnwrapRef<InnerFormInput> = reactive({
    Id: '',
    FormCode: '',
    FormName: '',
    FormPath: '',
    IsValid: true,
    Remark: ''
});

//列表
const columns = [
    { title: '表单名称', dataIndex: 'FormName' },
    { title: '表单编码', dataIndex: 'FormCode' },
    { title: '表单路径', dataIndex: 'FormPath' },
    {
        title: '是否有效', dataIndex: 'IsValid', customRender: function ({ text }): VNode {
            return h('div', {
                style: {
                    color: 'red'
                }
            }, text == 1 ? '有效' : '无效');
        }
    },
    { title: '创建时间', dataIndex: 'CreateTime' }
]

// 筛选
const selectItem = ref([
    { title: '表单名称', key: 'FormName', type: 'input', itemWidth: '290px' },
    { title: '表单编码', key: 'FormCode', type: 'input', itemWidth: '290px' },
    { title: '表单路径', key: 'FormPath', type: 'input', itemWidth: '290px' }
])

// 规则
const rules = {
    FormName: [{ required: true, message: '请输入表单名称', trigger: 'change' }],
    FormCode: [{ required: true, message: '请输入表单编码', trigger: 'change' }],
    FormPath: [{ required: true, message: '请输入表单路径', trigger: 'change' }]
}

//新增
const add = () => {
    modal_visible.value = true;
    let code = CustomIdPrefix("Form");
    Object.keys(formState).forEach(key => {
        if (key === 'FormCode') {
            formState[key] = code;
        } else {
            formState[key] = ''; // 清空其他字段
        }
    });

    formState.IsValid = true;
}

const edit = (event: any, item: any) => {
    let selectItem = item;
    if (!selectItem) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectItem = selectedRows.value[0];
    }
    modal_visible.value = true;
    Object.assign(formState, selectItem);
}

//删除一条记录
const del = (event: any, id: any) => {
    let selectId = id;
    if (!selectId) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectId = selectedRows.value[0].Id;
    }
    deleteInnerForm({ flowFormId: selectId }).then(() => {
        message.success("删除成功!");
        layout.value.getData();
    }).catch(err => {
        message.error(err.message || "删除失败!")
        confirmLoading.value = false;
    })
}

//复制表单编码
const onCopyTableCode = async (event: any) => {
    try {
        await navigator.clipboard.writeText(formState.FormCode);
        message.success('复制成功！');
    } catch (err) {
        console.error('复制失败', err);
        message.error('复制失败，请手动复制');
    }
}

// 多选
const selectedRowKeys = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const singleSelection = ref<any[]>([]);
const onSelectChange = (keys: [], rows: any) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
    singleSelection.value = rows[0];
}

const modal_handleOk = () => {
    formRef.value.validate().then(() => {
        confirmLoading.value = true;
        saveOrUpdateInnerForm(formState).then(e => {
            message.success("操作成功！");
            confirmLoading.value = false;
            modal_visible.value = false;
            layout.value.getData();
        }).catch(err => {
            message.error(err.message || "操作失败!")
            confirmLoading.value = false;
        })
    }).catch(() => {
        message.error('请检查必填项是否全部填写!');
    })
}

const labelCol = { span: 6 };
const wrapperCol = { span: 18 };
</script>


<style lang="scss">

.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1;
            flex-shrink: 0;
        }
    }
}
</style>